package com.aliyun.heiyu.common.util;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.URI;

/**
 * @Author czx
 * @Description
 * @Version 2019-01-01 22:13
 */
public class HttpUtil {
    private static Logger logger = LoggerFactory.getLogger(HttpUtil.class);

    public static String postJson(String url,String token,  String json) throws IOException {
        CloseableHttpClient httpClient = SkipHttpsUtil.getHttpClient();

        //设置请求超时时间和传输超时时间
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(500).setConnectTimeout(50).build();
        HttpPost post = new HttpPost(url);
        post.setConfig(requestConfig);
        post.addHeader("Content-Type", "application/json");
        post.addHeader("token", token);

        StringEntity se = new StringEntity(json);
        post.setEntity(se);

        CloseableHttpResponse httpResponse = null;
        try {
            httpResponse = httpClient.execute(post);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (httpResponse != null && statusCode == HttpStatus.SC_OK){
                HttpEntity entity = httpResponse.getEntity();
                if (entity != null) {
                    return EntityUtils.toString(entity, "utf-8");
                }
            }
        } catch (Exception e){
            logger.error(e.getMessage(), e);
        } finally {
            closeHttpClient(httpClient);
        }

        return null;
    }

    public static JSONObject getRequest(String url)throws Exception {
        JSONObject jsonobj = null;
        CloseableHttpClient httpclient = SkipHttpsUtil.getHttpClient();
        CloseableHttpResponse response = null;
        try {
            HttpGet httpget = new HttpGet(url);
            response = httpclient.execute(httpget);
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                return null;
            }
            //通过EntityUtils工具类将响应获取实体转成jsonobj
            jsonobj = new JSONObject(EntityUtils.toString(response.getEntity()));
        } catch (Exception e){
            logger.error(e.getMessage(), e);
        } finally {
            closeHttpClient(httpclient);
        }
        return  jsonobj;
    }

    public static JSONObject postRequest(String json,String host){
        JSONObject jsonobj = null;
        CloseableHttpClient httpclient = SkipHttpsUtil.getHttpClient();
        //CloseableHttpClient httpclient = SkipHttpsUtil.wrapClient();
        //创建http连接调用第三方接口
        try {
            HttpPost httpPost = new HttpPost(host);
            //设置请求超时时间和传输超时时间
            if(json!=null){
                StringEntity requestEntity = new StringEntity(json);
                requestEntity.setContentEncoding("UTF-8");
                requestEntity.setContentType("application/json");
                //使用post请求将json数据作为请求体
                httpPost.setEntity(requestEntity);
            }
            //发送请求，处理响应
            CloseableHttpResponse response = httpclient.execute(httpPost);
            try {
                //判断响应码，看是否请求成功
                if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                    return null;
                }
                jsonobj = new JSONObject(EntityUtils.toString(response.getEntity()));
            } finally {
                response.close();
            }
        } catch (Exception e){
            logger.error(e.getMessage(), e);
        } finally {
            closeHttpClient(httpclient);
        }
        return jsonobj;
    }

    public static JSONObject getHttpsRequest(String url) {
        JSONObject jsonobj = null;
        CloseableHttpClient httpclient = SkipHttpsUtil.getHttpClient();
        CloseableHttpResponse response = null;
        try {

            logger.info("url == "+LogUtils.vaildlog(url));
            HttpGet httpget = new HttpGet(url);
            response = httpclient.execute(httpget);
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                return null;
            }
            //通过EntityUtils工具类将响应获取实体转成jsonobj
            jsonobj = new JSONObject(EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            closeHttpClient(httpclient);
        }
        return  jsonobj;
    }

    public static JSONObject getRequest(URI url) {
        JSONObject jsonobj = null;
        CloseableHttpClient httpclient = SkipHttpsUtil.getHttpClient();
        CloseableHttpResponse response = null;
        try {
            HttpGet httpget = new HttpGet(url);
            response = httpclient.execute(httpget);
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                return null;
            }
            //通过EntityUtils工具类将响应获取实体转成jsonobj
            jsonobj = new JSONObject(EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            closeHttpClient(httpclient);
        }
        return  jsonobj;
    }

    public static String getRequestString(String url) {
        String result = "";
        CloseableHttpClient httpclient = SkipHttpsUtil.getHttpClient();
        CloseableHttpResponse response = null;
        try {
            HttpGet httpget = new HttpGet(url);
            response = httpclient.execute(httpget);
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                return "";
            }
            //通过EntityUtils工具类将响应获取实体转成jsonobj
            result = EntityUtils.toString(response.getEntity());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            closeHttpClient(httpclient);
        }
        return result;
    }

    public static String encoderURL(String url){
        return url.replace("&", "\\&");
    }

    private static void closeHttpClient(CloseableHttpClient client) {
        if (client != null) {
            try {
                client.close();
            } catch (Exception e){
                logger.error(e.getMessage(), e);
            }
        }
    }
}
